import store from '../store/index.js'
let code
let userInfo
let newCode
let werunIv
let werunEncryptedData
let werunCode
// 获取用户信息
function userLogin(){
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			success(res) {
				console.log(res,'code');
				code = res.code
				uni.getUserInfo({
					provider: 'weixin',
					async success(res) {
						console.log(res,'我执行了');
						userInfo = res 
						console.log(res.userInfo,'用户信息')
						store.commit('updataUserInfo',res.userInfo)
						uni.setStorageSync("userInfo",res.userInfo)
						await testLogin()
						await newInfo()
						await login()
						console.log('6666666666666666666');
						return 1
						resolve()
					},
					fail(res) {
						console.log(res,'授权失败')
						resolve()
					}
				})
			}
		})
	})
	
}
// 授权注册
function testLogin(){
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '授权登录中',
		});
		let self = this
		uni.request({
			url:store.state.URL + 'login/Login/mini_program_authorization',
			data:{
				code: code,
				iv: userInfo.iv,
				encryptedData: userInfo.encryptedData,
			},
			method:"POST",
			success(res) {
				uni.hideLoading();
				resolve()
			}
		})
		console.log('授权注册');
	})
}
// 重新获取code
function newInfo(){
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			success: function (loginRes) {
				newCode = loginRes.code;
				// 获取用户信息
				uni.getUserInfo({
					provider: 'weixin',
					success: function (infoRes) {
						console.log(infoRes,'infoRes');
						resolve()
					}
				});
			}
		});
	})
}
// 登录中
function login(){
	return new Promise((resolve, reject) => {
		let self = this
		uni.request({
			url:store.state.URL + 'login/Login/mini_program_login',
			data:{
				code: newCode,
			},
			method:"POST",
			success(res) {
				console.log(res,'授权登录成功');
				if(res.data.status) {
					store.commit('updataToken',res.data.token);
					store.commit('updataUserId',res.data.wx_user.id);
					// 将用户的id保存在本地存储
					uni.setStorageSync("userId",res.data.wx_user.id)
					uni.setStorageSync("phone",res.data.wx_user.phone)
					uni.showToast({
						title: '授权登录成功！',
						icon: 'none',
						duration: 2000
					})
				}
				console.log('用户登录后的数据',res.data)
				resolve()
			}
		})
	})
}
// 检查是否已授权
function testGet(){
	uni.getSetting({
		success(res) {
			console.log(res)
			if(!res.authSetting['scope.userInfo']){
				newInfo()
				uni.showToast({
					title:"请先登录",
					icon:"none",
					duration:2000
				})
			}else{
				console.log('11111111111111')
			}
		},
		fail(err) {
			console.log(err)
		}
	})
}
module.exports = {
	userLogin,
	testGet,
	login
}